<template>
  <div id="long-label"
    style="width:100%;height:100%"></div>
</template>

<script>
  import * as echarts from 'echarts';

  export default {
    name: 'ChartDatazoom',
    props: {
      objdata: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      objdata(obj) {
        let { data, xAxisData } = obj;
        this.bardata = data;
        this.xAxisData = xAxisData;
        this.initChart();
      }
    },
    data() {
      return {
        xAxisData: [],
        bardata: []
      };
    },
    created() {},
    methods: {
      initChart() {
        const dom = document.getElementById('long-label');
        if (dom) {
          //柱状图初始化
          const chart = echarts.init(dom);
          let options = {
            tooltip: {
              trigger: 'item'
            },
            grid: {
              top: '20',
              left: '50',
              right: '20',
              bottom: '40'
            },
            xAxis: {
              type: 'category',
              data: this.xAxisData,
              axisLabel: {
                interval: 0, //标签设置为全部显示
                formatter: function (val) {
                  // 这是回调函数，参数是label中的文字
                  let charArr = val.split('');
                  console.log(charArr);
                  let str = '',
                    num = 1;
                  for (let i = 0; i < charArr.length; i++) {
                    str += charArr[i];
                    if (num % 8 === 0) str += '\n'; //每隔8个字换行
                    num++;
                  }
                  console.log(str);
                  return str;
                }
              }
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: this.bardata,
                type: 'bar',
                barWidth: 30,
                itemStyle: {
                  normal: {
                    color: new echarts.graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 0,
                          color: '#0B80D8' // 0% 处的颜色
                        },
                        {
                          offset: 1,
                          color: 'rgba(11,131,222,0.51)' // 100% 处的颜色
                        }
                      ],
                      false
                    ),
                    barBorderRadius: [6, 6, 0, 0]
                  }
                }
              }
            ]
          };
          chart.setOption(options);
        }
      }
    }
  };
</script>